<template>
  <div class="content">
    <div class="header">
      <h3 class="title">用户列表</h3>
      <el-button type="primary" @click="handleNewUserClick" v-if="isCreate">新建用户</el-button>
    </div>

    <div class="table">
      <el-table :data="usersList" border style="width: 100%">
        <el-table-column align="center" type="selection" width="50px" />
        <el-table-column align="center" type="index" label="序号" width="60px" />

        <el-table-column align="center" label="用户名" prop="name" width="120px" />
        <el-table-column align="center" label="真实姓名" prop="realname" width="100px" />
        <el-table-column align="center" label="手机号码" prop="cellphone" width="140px" />
        <el-table-column align="center" label="状态" prop="enable" width="70px">
          <template #default="scope"
            ><el-button size="small" :type="scope.row.enable ? 'primary' : 'danger'" plain>{{
              scope.row.enable ? '启用' : '禁用'
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createAt">
          <template #default="scope">
            {{ formatUTC(scope.row.createAt) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间" prop="updateAt">
          <template #default="scope">
            {{ formatUTC(scope.row.updateAt) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="150px">
          <template #default="scope">
            <el-button
              size="small"
              icon="Edit"
              type="primary"
              text
              @click="handleEditBtnClick(scope.row)"
              v-if="isUpdate"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              text
              @click="handleDeleteBtnClick(scope.row.id)"
              v-if="isDelete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 确认框  -->
    <div>
      <el-dialog v-model="dialogVisible" title="删除提示" width="30%">
        <span>您确定要删除该数据吗？</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCancelBtnClick()" style="margin-right: 10px">取消</el-button>
            <el-button type="primary" @click="handleOkBtnClick()"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total,sizes,prev,pager,next,jumper"
        :total="usersTotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import useSystemStore from '@/store/main/system/system'
import { formatUTC } from '@/utils/format'
import { ref } from 'vue'
import usePermissions from '@/hooks/usePermissions'

const currentPage = ref(1)
const pageSize = ref(10)

// 定义事件
const emit = defineEmits(['newClick', 'editClick'])

// 用户的权限判断
const isCreate = usePermissions('users:create')
const isDelete = usePermissions('users:delete')
const isUpdate = usePermissions('users:update')
const isQuery = usePermissions('users:query')

// 1.发起action，请求usersList的数据
const systemStore = useSystemStore()
fetchUserListData()

// 2.获取usersList数据,进行展示
const { usersList, usersTotalCount } = storeToRefs(systemStore)

// 页码相关的逻辑
function handleSizeChange() {
  // console.log('page-size-change', pageSize.value)
  fetchUserListData()
}
function handleCurrentChange() {
  // console.log('current-page-change', currentPage.value)
  fetchUserListData()
}

// 定义函数，用于发送网络请求
function fetchUserListData(formData: any = {}) {
  if (!isQuery) return
  // 获取offset和size
  const size = pageSize.value
  const offset = (currentPage.value - 1) * size
  const info = { size, offset }
  const queryInfo = { ...info, ...formData }
  console.log(queryInfo)
  systemStore.postUsersListAction(queryInfo)
}

// 确认框弹出或关闭
const dialogVisible = ref(false)

// 处理删除功能
let deleteId = 0
function handleDeleteBtnClick(id) {
  dialogVisible.value = true
  deleteId = id
}

// 确认框确定操作
function handleOkBtnClick() {
  systemStore
    .deleteUserByIdAction(deleteId)
    .then((res) => {
      if (res !== -1002) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
      } else {
        ElMessage({
          message: '删除失败，请稍后重试',
          type: 'warning'
        })
      }
    })
    .catch((err) => {
      ElMessage({
        message: '删除失败，请稍后重试',
        type: 'warning'
      })
    })
  dialogVisible.value = false
  currentPage.value = 1
}

// 确认框取消操作
function handleCancelBtnClick() {
  dialogVisible.value = false
}

// 新建用户的操作
function handleNewUserClick() {
  emit('newClick')
}

// 处理编辑事务
function handleEditBtnClick(itemData) {
  emit('editClick', itemData)
  currentPage.value = 1
}

// 将fetchUserListData方法暴露出去，才能通过组件ref.value查到
defineExpose({ fetchUserListData })
</script>

<style lang="less" scoped>
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;

  .title {
    font-size: 22px;
  }
}

.table {
  :deep(.el-table__cell) {
    padding: 12px 0;
  }

  .el-button {
    margin-left: 0;
    padding: 5px 8px;
  }
}
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0 0;
}
</style>
